package cn.com.dycc.task_manage.orderdeal.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.dycc.common.attach.dao.AttachDao;
import cn.com.dycc.common.attach.entity.Attach;
import cn.com.dycc.common.log.Constants;
import cn.com.dycc.common.log.SystemServiceLog;
import cn.com.dycc.party_org.organize.service.NotFoundOrganizeException;
import cn.com.dycc.task_manage.orderdeal.dao.OrderDealDao;
import cn.com.dycc.task_manage.orderdeal.entity.NewFindOrderDeal;
import cn.com.dycc.task_manage.orderdeal.param.DealUserAndDept;
import cn.com.dycc.task_manage.orderdeal.param.FindOrdealineParam;
import cn.com.dycc.task_manage.orderdeal.param.ListAttachAndUserDept;
import cn.com.dycc.task_manage.orderdeal.param.NewOrderDealParam;
import cn.com.dycc.task_manage.orderdeal.param.OrderDealParam;
import cn.com.dycc.task_manage.orderdeal.param.UpdateOrderParam;
import cn.com.dycc.task_manage.ordermain.dao.OrderMainDao;
import cn.com.dycc.task_manage.ordermain.entity.WorkOrdealInfor;
import cn.com.dycc.task_manage.ordermain.service.NotFoundOrderMainException;
import cn.com.dycc.util.AttachUtil;
import cn.com.dycc.util.DateUtil;
import cn.com.dycc.util.FileUtil;
import cn.com.dycc.util.IntegerUtil;
import cn.com.dycc.util.Paging;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("orderDealService")
@Transactional(rollbackFor=Exception.class)
public class OrderDealServiceImpl implements OrderDealService{
	
	@Resource(name="orderDealDao")
	private OrderDealDao orderDealDao;
	
	@Resource(name="orderMainDao")
	private OrderMainDao orderMainDao;
	
	@Resource(name="paging")
	private Paging paging;
	
	@Resource(name="attachDao")
	private AttachDao attachDao;
	
	
	//查询工单细表信息
	public List<WorkOrdealInfor> findOrDealByUserId(HttpServletRequest request, FindOrdealineParam findOrdealineParam)
			throws NotFoundOrderDealException {
		
		String org_id = request.getSession().getAttribute("org_id").toString();
		
		String deal_user_id = request.getSession().getAttribute("id").toString();
		if(deal_user_id==null){
			throw new NotFoundOrderDealException("请登录！");
		}
		
		Integer limit = findOrdealineParam.getLimit();
		Integer page = findOrdealineParam.getPage();
		
		if(!(IntegerUtil.isNumeric(page.toString()))){
			throw new NotFoundOrganizeException("查询页码为整型！");
		}
		
		Integer start = null;
		if(limit==null&&page!=null){
			limit = paging.getPageSize();
			start=(page-1)*limit;
		}
		if(page==null){
			start = null;
			limit = null;
		}
		if(limit!=null&&page!=null){
			start = limit*(page-1);
		}
		
		findOrdealineParam.setOrder_status("2");
		findOrdealineParam.setDeal_order_status("2");
		findOrdealineParam.setDeal_user_id(deal_user_id);
		findOrdealineParam.setOrg_id(org_id);
		findOrdealineParam.setLimit(limit);
		findOrdealineParam.setStart(start);

		return orderDealDao.findOrDealByUserId(findOrdealineParam);
	}

	////查询工单细表信息 统计
	public String findOrDealByUserIdCount(HttpServletRequest request, FindOrdealineParam findOrdealineParam)
			throws NotFoundOrderDealException {
		
		String org_id = request.getSession().getAttribute("org_id").toString();
		
		String deal_user_id = request.getSession().getAttribute("id").toString();
		if(deal_user_id==null){
			throw new NotFoundOrderDealException("请登录！");
		}
		
		findOrdealineParam.setOrder_status("2");
		findOrdealineParam.setDeal_order_status("2");
		findOrdealineParam.setDeal_user_id(deal_user_id);
		findOrdealineParam.setOrg_id(org_id);
		
		return orderDealDao.findOrDealByUserIdCount(findOrdealineParam);
	}
	
	//查询未处理工单细表信息
	public List<WorkOrdealInfor> findOrDealNotByUserId(HttpServletRequest request,
			FindOrdealineParam findOrdealineParam) throws NotFoundOrderDealException {
		String org_id = request.getSession().getAttribute("org_id").toString();
		
		String deal_user_id = request.getSession().getAttribute("id").toString();
		if(deal_user_id==null){
			throw new NotFoundOrderDealException("请登录！");
		}
		
		Integer limit = findOrdealineParam.getLimit();
		Integer page = findOrdealineParam.getPage();
		
		if(!(IntegerUtil.isNumeric(page.toString()))){
			throw new NotFoundOrganizeException("查询页码为整型！");
		}
		
		Integer start = null;
		if(limit==null&&page!=null){
			limit = paging.getPageSize();
			start=(page-1)*limit;
		}
		if(page==null){
			start = null;
			limit = null;
		}
		if(limit!=null&&page!=null){
			start = limit*(page-1);
		}
		
		findOrdealineParam.setOrder_status("1");
		findOrdealineParam.setDeal_order_status("1");
		findOrdealineParam.setDeal_user_id(deal_user_id);
		findOrdealineParam.setOrg_id(org_id);
		findOrdealineParam.setLimit(limit);
		findOrdealineParam.setStart(start);

		return orderDealDao.findOrDealByUserId(findOrdealineParam);
	}
	
	//查询未处理工单细表信息 统计
	public String findOrNotDealByUserIdCount(HttpServletRequest request, FindOrdealineParam findOrdealineParam)
			throws NotFoundOrderDealException {
		String org_id = request.getSession().getAttribute("org_id").toString();
		
		String deal_user_id = request.getSession().getAttribute("id").toString();
		if(deal_user_id==null){
			throw new NotFoundOrderDealException("请登录！");
		}
		
		findOrdealineParam.setOrder_status("1");
		findOrdealineParam.setDeal_order_status("1");
		findOrdealineParam.setDeal_user_id(deal_user_id);
		findOrdealineParam.setOrg_id(org_id);
		
		return orderDealDao.findOrDealByUserIdCount(findOrdealineParam);
	}
	
	//处理工单并且发送给下一节点
	@SystemServiceLog(description=Constants.ORDER_DEAL)
	public String updateAndSend(HttpServletRequest request,ListAttachAndUserDept listAttachAndUserDept)
			throws NotFoundOrderDealException {
		
		String org_id = request.getSession().getAttribute("org_id").toString();
		
		String send_user_id = request.getSession().getAttribute("id").toString();
		if(send_user_id==null){
			throw new NotFoundOrderDealException("请登录！");
		}
		
		//用户和部门
		List<DealUserAndDept> listDealUserAndDept = listAttachAndUserDept.getListDealUserAndDept();
		
		//附件
		List<Attach> list = listAttachAndUserDept.getList();
		
		OrderDealParam orderDealParam = listAttachAndUserDept.getOrderDealParam();
		
		if(orderDealParam.getSerial_no()==null||orderDealParam.getSerial_no().trim().isEmpty()){
			throw new NotFoundOrderDealException("请选择需要处理的工单！");
		}
		
		
		//是否已被处理
		if(!("1".equals(orderDealDao.findOrderStatusById(orderDealParam.getSerial_no(),org_id)))){
			throw new NotFoundOrderDealException("工单已被处理，请确认！");
		}
		
		if("2".equals(orderDealParam.getOrder_status())||"1".equals(orderDealParam.getOrder_status())){
			if(orderDealParam.getContent()==null||orderDealParam.getContent().trim().isEmpty()){
				throw new NotFoundOrderDealException("请填写处理内容！");
			}
		}else if("3".equals(orderDealParam.getOrder_status())){
			if(orderDealParam.getContent()==null||orderDealParam.getContent().trim().isEmpty()){
				orderDealParam.setContent("回退上一节点");
			}
		}
		
		if(orderDealParam.getOrder_status()==null||orderDealParam.getOrder_status().trim().isEmpty()){
			throw new NotFoundOrderDealException("请填写处理状态");
		}
		
		if(!(IntegerUtil.isNumeric(orderDealParam.getOrder_status()))){
			throw new NotFoundOrganizeException("状态类型为整型！");
		}
		
		String format = "yyyy-MM-dd HH:mm:ss";
		String finish_date = DateUtil.getNowDate(format);
		
		UpdateOrderParam updateOrderParam = new UpdateOrderParam();
		updateOrderParam.setContent(orderDealParam.getContent());
		updateOrderParam.setFinish_date(finish_date);
		updateOrderParam.setOrder_status(orderDealParam.getOrder_status());
		updateOrderParam.setSerial_no(orderDealParam.getSerial_no());
		updateOrderParam.setOrder_status("2");
		updateOrderParam.setOrg_id(org_id);
		
		int updeal = orderDealDao.updateOrderDeal(updateOrderParam);
		if(updeal==0){
			throw new NotFoundOrganizeException("处理工单失败！请稍后重试");
		}
		
		List<OrderDealParam> listOrderDealParam = new ArrayList<OrderDealParam>();
		
		if("2".equals(orderDealParam.getOrder_status())){
			//如果当前节点是做归档操作，判断全部节点是否归档，主表改变状态
			List<String> listString = orderDealDao.findOrderStatusByOrderId(orderDealParam.getOrder_id(),org_id);
			boolean flag = true;
			for(String status : listString){
				if("1".equals(status)){
					flag = false;
					break;
				}
			}
			if(flag){
				int upmain = orderMainDao.updateOrderStatusByid(orderDealParam.getOrder_id(),finish_date,org_id);
				if(upmain==0){
					throw new NotFoundOrderMainException("发送失败！");
				}
			}
		}else{
			for(DealUserAndDept dua : listDealUserAndDept){
				OrderDealParam odp = new OrderDealParam();
				odp.setOrder_id(orderDealParam.getOrder_id());
				odp.setDeal_pid(orderDealParam.getDeal_id());
				if(dua.getDeal_user_id()==null||dua.getDeal_user_id().trim().isEmpty()){
					throw new NotFoundOrderMainException("请选择处理人！");
				}
				odp.setDeal_user_id(dua.getDeal_user_id());
			
				if(dua.getDept_id()==null||dua.getDept_id().trim().isEmpty()){
					throw new NotFoundOrderMainException("请选择处理人部门！");
				}
				odp.setDeal_dept_id(dua.getDept_id());
				
//				System.out.println("ce="+dua.getTime_limit());
//				System.out.println("ce2="+dua.getTime_limit().trim().isEmpty());
				if(!(dua.getTime_limit().trim().isEmpty())){
					odp.setTime_limit(dua.getTime_limit());
				}else{
					odp.setTime_limit(null);
				}
				odp.setRec_time(finish_date);
				odp.setState("Y");
				odp.setOrder_status("1");
				odp.setOpt_user_id(send_user_id);
				odp.setOrg_id(org_id);
				listOrderDealParam.add(odp);
			}
		
			int batch = orderDealDao.batchOrderDeal(listOrderDealParam);
		
			if(batch==0){
				throw new NotFoundOrderMainException("发送失败！");
			}
		}
		
		
		
//		//获取父节点
//		String deal_pid = orderDealParam.getDeal_pid();
//		//根据父节点查询该节点下的所有子节点状态
//		List<String> listString = orderDealDao.findOrderStatusByDealPid(deal_pid);
//		//如果所有的子状态都 不是已处理，不能执行下发或者是归档
//		boolean flag = true;
//		for(String status : listString){
//			if(!("1".equals(status))){
//				flag = false;
//				break;
//			}
//		}
//		//发送给子节点或者是归档
//		if(flag){
//			
//			List<OrderDealParam> listOrderDealParam = new ArrayList<OrderDealParam>();
//			
//			if("2".equals(orderDealParam.getOrder_status())){
//				int upmain = orderMainDao.updateOrderStatusByid(orderDealParam.getOrder_id(),finish_date);
//				if(upmain==0){
//					throw new NotFoundOrderMainException("发送失败！");
//				}
//			}else{
//				for(DealUserAndDept dua : listDealUserAndDept){
//					OrderDealParam odp = new OrderDealParam();
//					odp.setOrder_id(orderDealParam.getOrder_id());
//					odp.setDeal_pid(orderDealParam.getDeal_id());
//					if(dua.getDeal_user_id()==null||dua.getDeal_user_id().trim().isEmpty()){
//						throw new NotFoundOrderMainException("请选择处理人！");
//					}
//					odp.setDeal_user_id(dua.getDeal_user_id());
//					
//					if(dua.getDept_id()==null||dua.getDept_id().trim().isEmpty()){
//						throw new NotFoundOrderMainException("请选择处理人部门！");
//					}
//					odp.setDeal_dept_id(dua.getDept_id());
//					
//					if(!("null".equals(orderDealParam.getTime_limit()))||!(orderDealParam.getTime_limit().trim().isEmpty())){
//						odp.setTime_limit(dua.getTime_limit());
//					}
//					odp.setRec_time(finish_date);
//					odp.setState("Y");
//					odp.setOrder_status("1");
//					odp.setOpt_user_id(send_user_id);
//					odp.setOrg_id(org_id);
//					listOrderDealParam.add(odp);
//				}
//				
//				int batch = orderDealDao.batchOrderDeal(listOrderDealParam);
//				
//				if(batch==0){
//					throw new NotFoundOrderMainException("发送失败！");
//				}
//			}
//		}
		
		//将上传的图片流转换为附件字段
		List<Attach> listAttach = new ArrayList<Attach>();
		//附件移到正式文件夹
		List<Attach> newListAttach = new ArrayList<Attach>();
	//	System.out.println("l="+listAttach.size());
        if (list != null&&list.size()!=0) {  
        	JSONArray json=JSONArray.fromObject(list);
 //       	System.out.println("jo="+json.size());
			for(int i=0;i<json.size();i++){
//				System.out.println("打桩1111111111111");
//				System.out.println("打桩2："+json.get(i));
				Object check=json.get(i);
				if("null".equals(check.toString())){
					continue;
				}
				JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
				
	//			System.out.println("job"+job);
				String attach_ext=(String)job.get("attach_ext");
				String attach_path=(String)job.get("attach_path");
				String attach_size=(String)job.get("attach_size");
				String title=(String)job.get("title");
				Attach attach=new Attach();
				attach.setMessage_no(orderDealParam.getOrder_id());
				attach.setAttach_type(Integer.valueOf(AttachUtil.order_main_attach_type));
				attach.setTitle(title);
				attach.setAttach_ext(attach_ext);
				attach.setAttach_path(attach_path);
				attach.setAttach_size(attach_size);				
				attach.setOrg_id(org_id);
				attach.setOpt_user_id(send_user_id);
				listAttach.add(attach);
//				System.out.println(attach_ext);
//				System.out.println(attach_path);
//				System.out.println(attach_size);
//				System.out.println(title);	
			}
			newListAttach=FileUtil.moveFile(listAttach,"task_manage");
			int addAttach = attachDao.addAttachBatch(newListAttach);
			if(addAttach==0){
				throw new NotFoundOrderMainException("发送失败！");
			}
		}
		
		return "发送成功！";
	}
	
	//查询已处理的工单信息2018-07-25新起接口
	public List<NewFindOrderDeal> newFindOrderDeal(HttpServletRequest request,NewOrderDealParam newOrderDealParam)
			throws NotFoundOrderDealException {
		
		String org_id = request.getSession().getAttribute("org_id").toString();
		
		String deal_user_id = request.getSession().getAttribute("id").toString();
		if(deal_user_id==null){
			throw new NotFoundOrderDealException("请登录！");
		}
		
		Integer limit = newOrderDealParam.getLimit();
		Integer page = newOrderDealParam.getPage();
		
		if(!(IntegerUtil.isNumeric(page.toString()))){
			throw new NotFoundOrganizeException("查询页码为整型！");
		}
		
		Integer start = null;
		if(limit==null&&page!=null){
			limit = paging.getPageSize();
			start=(page-1)*limit;
		}
		if(page==null){
			start = null;
			limit = null;
		}
		if(limit!=null&&page!=null){
			start = limit*(page-1);
		}
		
		newOrderDealParam.setDeal_user_id(deal_user_id);
		newOrderDealParam.setOrg_id(org_id);
		newOrderDealParam.setLimit(limit);
		newOrderDealParam.setStart(start);
		newOrderDealParam.setDeal_order_status("2");

		return orderDealDao.newFindOrderDeal(newOrderDealParam);
	}
	
	//查询已处理的工单信息2018-07-25新起接口 统计
	public String newFindOrderDealCount(HttpServletRequest request, NewOrderDealParam newOrderDealParam)
			throws NotFoundOrderDealException {
		String org_id = request.getSession().getAttribute("org_id").toString();
		
		String deal_user_id = request.getSession().getAttribute("id").toString();
		if(deal_user_id==null){
			throw new NotFoundOrderDealException("请登录！");
		}
		
		newOrderDealParam.setDeal_user_id(deal_user_id);
		newOrderDealParam.setOrg_id(org_id);
		newOrderDealParam.setDeal_order_status("2");	
		return orderDealDao.newFindOrderDealCount(newOrderDealParam);
	}

}
